package com.limao.DbConnection;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

import com.limao.CacheManager.BaseDataCacheManager;
import com.limao.CacheManager.BuyIceTaskCacheManager;
import com.limao.CacheManager.CrowdCompanyCache;
import com.limao.CacheManager.CrowdHomeCommendCache;
import com.limao.CacheManager.CrowdOrderCache;
import com.limao.CacheManager.CrowdPrestigeGoodsCache;
import com.limao.CacheManager.CrowdPrestigeParmCache;
import com.limao.CacheManager.CrowdSmallCompanyCacheManager;
import com.limao.CacheManager.CrowdSysCateCache;
import com.limao.CacheManager.CrowdSysPriceCache;
import com.limao.CacheManager.CrowdSysProjectCache;
import com.limao.CacheManager.CrowdUserAuthCache;
import com.limao.CacheManager.CrowdVRHomeCache;
import com.limao.CacheManager.CrowdVRUserRmbCache;
import com.limao.CacheManager.HomeColumManager;
import com.limao.CacheManager.HomeStructureCacheManager;
import com.limao.CacheManager.IpCacheManager;
import com.limao.CacheManager.RmbwithdrawCacheManager;
import com.limao.CacheManager.SessionCacheManager;
import com.limao.CacheManager.SysGoodsCut_CacheManager;
import com.limao.CacheManager.SysRedbagCache;
import com.limao.CacheManager.SysRmbSelect_CacheManager;
import com.limao.CacheManager.SysSmsCacheManagr;
import com.limao.CacheManager.Sys_StudyCacheManager;
import com.limao.CacheManager.SyshonoraryCacheManage;
import com.limao.CacheManager.SyslevelManager;
import com.limao.CacheManager.Verson_CacheManager;
import com.limao.CacheManager.VrGoodsCache;
import com.limao.CacheManager.mobile_codeCacheManger;
import com.limao.CacheManager.sys_AdvCacheManager;
import com.limao.CacheManager.table_ideCacheManager;
import com.limao.CacheManager.user_addressCacheManager;
import com.limao.CacheManager.user_offline_CacheManager;
import com.limao.CacheManager.user_parentCacheManager;
import com.limao.CacheManager.user_rmbCacheManager;
import com.limao.CacheManager.usernumCacheManager;
import com.limao.Tool.CacheClass;
import com.limao.Tool.TaskOneForCd_Order;
import com.limao.Tool.TaskOneForCd_Order2;
import com.limao.Tool.TaskOneForVrAutoTrade_new;
import com.limao.Tool.TaskOneForVrPre_Order;
import com.limao.cache.Module;

public class lankServer {

	private static lankServer instance;
	private static Map<Class, Module> modules = new LinkedHashMap<Class, Module>();
	private static ClassLoader loader;
	
	static int vr_open_time=400;
	static int vr_close_time=800;
	
	static TaskOneForCd_Order task_CdOrder=null;
	
	static TaskOneForVrPre_Order task_VrOrder=null;
	
	static TaskOneForCd_Order2 task_CdOrder2=null;
	
	static TaskOneForVrAutoTrade_new  new_auto_trade=null;
	
	public static lankServer getInstance() {
		if(instance==null) new lankServer();
	     return instance;
	}
	   
	public lankServer()
	{
		instance = this;
	}
	
	
	public  void start()
	{
		modules.clear();
    	loader = Thread.currentThread().getContextClassLoader();
    	
     	TimeZone e8 = TimeZone.getTimeZone("GMT+8");
    	TimeZone.setDefault(e8);
    	
	  	DbConnectionManager.init();
    	verifyDataSource();
    		List<String> moduleList=new ArrayList<String>();
    		
    		moduleList.add(BaseDataCacheManager.class.getName());
    		moduleList.add(mobile_codeCacheManger.class.getName());
    		moduleList.add(CrowdOrderCache.class.getName());
    		moduleList.add(RmbwithdrawCacheManager.class.getName());
    		moduleList.add(SessionCacheManager.class.getName());
    		moduleList.add(CrowdSysProjectCache.class.getName());
    		moduleList.add(table_ideCacheManager.class.getName());
    		moduleList.add(user_addressCacheManager.class.getName());
    		moduleList.add(user_offline_CacheManager.class.getName());
    		moduleList.add(user_parentCacheManager.class.getName());
    		moduleList.add(user_rmbCacheManager.class.getName());
    		moduleList.add(CrowdUserAuthCache.class.getName());
    		moduleList.add(usernumCacheManager.class.getName());
    		moduleList.add(Verson_CacheManager.class.getName());
    		moduleList.add(SysGoodsCut_CacheManager.class.getName());
    		moduleList.add(CrowdSysCateCache.class.getName());

    		moduleList.add(HomeStructureCacheManager.class.getName());
    		moduleList.add(HomeColumManager.class.getName());
    		moduleList.add(HomeColumManager.class.getName());
    		moduleList.add(SyshonoraryCacheManage.class.getName());
    		
    		moduleList.add(CrowdPrestigeParmCache.class.getName());
    		moduleList.add(CrowdPrestigeGoodsCache.class.getName());
    		moduleList.add(BuyIceTaskCacheManager.class.getName());
    		
    		moduleList.add(CrowdSysPriceCache.class.getName());
    		
    		moduleList.add(SysRedbagCache.class.getName());
    		
    		
    		moduleList.add(SyslevelManager.class.getName());
    		moduleList.add(SysRmbSelect_CacheManager.class.getName());
    		moduleList.add(Sys_StudyCacheManager.class.getName());
    		moduleList.add(IpCacheManager.class.getName());
    		moduleList.add(SysSmsCacheManagr.class.getName());
    		
    		moduleList.add(sys_AdvCacheManager.class.getName());
    		moduleList.add(CrowdHomeCommendCache.class.getName());
    		moduleList.add(CrowdCompanyCache.class.getName());
    		moduleList.add(CrowdVRHomeCache.class.getName());
    		moduleList.add(CrowdVRUserRmbCache.class.getName());
    		
    		moduleList.add(CrowdSmallCompanyCacheManager.class.getName());
    		moduleList.add(VrGoodsCache.class.getName());
    		
    		
    		
    		loadModule(moduleList);
    	    initModules();
    	    startModules();
  	    
      	    //开盘时间
    	    vr_open_time=CacheClass.getIntValue(CacheClass.getSYS_BaseDataCacheManager().Load_Param("vr_open_time").trim());
    	    //停盘时间
    	    vr_close_time=CacheClass.getIntValue(CacheClass.getSYS_BaseDataCacheManager().Load_Param("vr_close_time").trim());
    	    
    	    
    	    Date currenDate=new Date();
			Calendar orderTime = Calendar.getInstance();
			orderTime.setTime(currenDate);
			orderTime.set(Calendar.HOUR_OF_DAY, 0);
			orderTime.set(Calendar.MINUTE, 0);
			orderTime.set(Calendar.SECOND, 0);  
			orderTime.set(Calendar.MILLISECOND, 0);
			orderTime.add(Calendar.MINUTE, 24*60); //加1天
			Date orderDate = orderTime.getTime();
    		if(CacheClass.task ==1) //是否开启定时任务 0否   1是
    		{
    			System.out.println("定时任务  是");
	    		task_CdOrder=new TaskOneForCd_Order();
	    		new java.util.Timer().scheduleAtFixedRate(task_CdOrder, orderDate,24*3600*1000); //每隔24小时检测执行一次
	    		
	    		task_CdOrder2=new TaskOneForCd_Order2();
	    		new java.util.Timer().scheduleAtFixedRate(task_CdOrder2, 10*1000,60*1000); //每隔60秒检测执行一次
	    		
	    		new_auto_trade=new TaskOneForVrAutoTrade_new();
	    		new java.util.Timer().scheduleAtFixedRate(new_auto_trade, 0,10*1000); //每隔24小时检测执行一次
	    		
	    		
	    	    //取得开盘的分钟，只便计算定时任务的开启时间点
	    	   int openMinute=vr_open_time%100;
	    	   int openHour=vr_open_time/100;
	    	    //取得停盘的分钟，只便计算定时任务的开启时间点
	    	   
	    	   int vr_curren_time=CacheClass.getHm_int(currenDate);
	    	   if(vr_curren_time<vr_open_time)
	    	   {
					orderTime.setTime(currenDate);
					orderTime.set(Calendar.HOUR_OF_DAY, openHour);
					orderTime.set(Calendar.MINUTE, openMinute);
					orderTime.set(Calendar.SECOND, 0);  
					orderTime.set(Calendar.MILLISECOND, 0);
					orderDate = orderTime.getTime();
					
		    		task_VrOrder=new TaskOneForVrPre_Order();
		    		new java.util.Timer().scheduleAtFixedRate(task_VrOrder, orderDate,24*3600*1000); //每隔24小时检测执行一次
		    		
	    	   }
	    	   else
	    	   {
					orderTime.setTime(currenDate);
					orderTime.set(Calendar.HOUR_OF_DAY, openHour);
					orderTime.set(Calendar.MINUTE, openMinute);
					orderTime.set(Calendar.SECOND, 0);  
					orderTime.set(Calendar.MILLISECOND, 0);
					orderTime.add(Calendar.MINUTE, 24*60); //加1天
					orderDate = orderTime.getTime();
		    		task_VrOrder=new TaskOneForVrPre_Order();
		    		new java.util.Timer().scheduleAtFixedRate(task_VrOrder, orderDate,24*3600*1000); //每隔24小时检测执行一次
		    		
	    	   }
	    		 
    		}
    		

	}

	
	
	
    public  void loadModule(List<String> moduleList) {
    	
        try {
        	for(String module:moduleList){
        		
	            Class<?> modClass = loader.loadClass(module);
	            Module mod = (Module) modClass.newInstance();
	            modules.put(modClass, mod);
        	}
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
	

	    private  void initModules() {
	        for (Module module : modules.values()) {
	            boolean isInitialized = false;
	            try {
	                module.initialize();
	                isInitialized = true;
	            }
	            catch (Exception e) {
	                e.printStackTrace();
	                // Remove the failed initialized module
	                modules.remove(module.getClass());
	                if (isInitialized) {
	                    module.stop();
	                    module.destroy();
	                }
	            }
	        }
	    }

	    private  void startModules() {
	        for (Module module : modules.values()) {
	            boolean started = false;
	            try {
	                module.start();
	            }
	            catch (Exception e) {
	                if (started && module != null) {
	                    module.stop();
	                    module.destroy();
	                }
	            }
	        }
	    }
	    
	
	
	public  void stop()
	{
		if(task_CdOrder!=null ) {task_CdOrder.cancel();task_CdOrder=null;}
		if(task_CdOrder2!=null ) {task_CdOrder2.cancel();task_CdOrder2=null;}
		if(new_auto_trade!=null ) {new_auto_trade.cancel();new_auto_trade=null;}
		if(task_VrOrder!=null ) {task_VrOrder.cancel();task_VrOrder=null;}
		
		DbConnectionManager.destroyConnectionProvider();
	}
	
	
	
	
	private  void verifyDataSource() 
	{
        Connection con = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            con = DbConnectionManager.getConnection();
            pstmt = con.prepareStatement("SELECT 1");
            rs = pstmt.executeQuery();
            rs.next();
        }
        catch (Exception e) {
            System.err.println("Database setup or configuration error: " +
                    "Please verify your database settings and check the " +
                    "logs/error.log file for detailed error messages.");
            throw new IllegalArgumentException(e);
        }
        finally {
            DbConnectionManager.closeConnection(rs, pstmt, con);
        }
	}

 


}
